package com.park.common.util;

import com.park.common.constant.IDBConstant;
import com.park.common.constant.IPlatformConstant;
import com.park.common.po.OtherResource;
import org.apache.log4j.Logger;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.io.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * Created by baby on 15/6/2.
 */

public class FileUploader {

    private static final Logger logger = Logger.getLogger(FileUploader.class);

    private String path;

    private String receivableImagesPath;

    private String receivableSoundPath;

    private String projectTemplatePath;

    private String emailFilePath;

    private String autoProjectFilePath;

    private String pledgeFilePath;

    private String assetPackagingFilePath;

    private String cmsFilePath;

    private String cmsImagesFilePath;

    private String cmsAccessURL;

    private String cmsImagesAccessURL;

    private String domainURL;

    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }

    public String getReceivableImagesPath() {
        return receivableImagesPath;
    }

    public void setReceivableImagesPath(String receivableImagesPath) {
        this.receivableImagesPath = receivableImagesPath;
    }

    public String getReceivableSoundPath() {
        return receivableSoundPath;
    }

    public void setReceivableSoundPath(String receivableSoundPath) {
        this.receivableSoundPath = receivableSoundPath;
    }

    public String getProjectTemplatePath() {
        return projectTemplatePath;
    }

    public void setProjectTemplatePath(String projectTemplatePath) {
        this.projectTemplatePath = projectTemplatePath;
    }

    public String getEmailFilePath() {
        return emailFilePath;
    }

    public void setEmailFilePath(String emailFilePath) {
        this.emailFilePath = emailFilePath;
    }

    public String getAutoProjectFilePath() {
        return autoProjectFilePath;
    }

    public void setAutoProjectFilePath(String autoProjectFilePath) {
        this.autoProjectFilePath = autoProjectFilePath;
    }

    public String getPledgeFilePath() {
        return pledgeFilePath;
    }

    public void setPledgeFilePath(String pledgeFilePath) {
        this.pledgeFilePath = pledgeFilePath;
    }

    public String getAssetPackagingFilePath() {
        return assetPackagingFilePath;
    }

    public void setAssetPackagingFilePath(String assetPackagingFilePath) {
        this.assetPackagingFilePath = assetPackagingFilePath;
    }

    public String getCmsFilePath() {
        return cmsFilePath;
    }

    public void setCmsFilePath(String cmsFilePath) {
        this.cmsFilePath = cmsFilePath;
    }

    public String getCmsImagesFilePath() {
        return cmsImagesFilePath;
    }

    public void setCmsImagesFilePath(String cmsImagesFilePath) {
        this.cmsImagesFilePath = cmsImagesFilePath;
    }

    public String getCmsAccessURL() {
        return cmsAccessURL;
    }

    public void setCmsAccessURL(String cmsAccessURL) {
        this.cmsAccessURL = cmsAccessURL;
    }

    public String getCmsImagesAccessURL() {
        return cmsImagesAccessURL;
    }

    public void setCmsImagesAccessURL(String cmsImagesAccessURL) {
        this.cmsImagesAccessURL = cmsImagesAccessURL;
    }

    public String getDomainURL() {
        return domainURL;
    }

    public void setDomainURL(String domainURL) {
        this.domainURL = domainURL;
    }

    public void saveToRootDisc(InputStream inputStream, String fold, String fileName) {
        BufferedOutputStream out = null;
        try {
            File pictureFile = new File(fold + "/" + fileName); //File.separator
            File parentFile = new File(pictureFile.getParent());
            if (!parentFile.exists()) {
                parentFile.mkdirs();
            }
            if (!pictureFile.exists()) {
                pictureFile.createNewFile();
            }
            //inputStream.reset();
            out = new BufferedOutputStream(new FileOutputStream(pictureFile));
            int readBytes = 0;
            byte[] buffer = new byte[8192];
            while ((readBytes = inputStream.read(buffer, 0, buffer.length)) != -1) {
                out.write(buffer, 0, readBytes);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (out != null) {
                try {
                    out.flush();
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public void saveToDisc(InputStream inputStream, String fold, String fileName) {
        BufferedOutputStream out = null;
        try {
            File pictureFile = new File(path + File.separator + fold + File.separator + fileName);
            File parentFile = new File(pictureFile.getParent());
            if (!parentFile.exists()) {
                parentFile.mkdirs();
            }
            if (!pictureFile.exists()) {
                pictureFile.createNewFile();
            }
            //inputStream.reset();
            out = new BufferedOutputStream(new FileOutputStream(pictureFile));
            int readBytes = 0;
            byte[] buffer = new byte[8192];
            while ((readBytes = inputStream.read(buffer, 0, buffer.length)) != -1) {
                out.write(buffer, 0, readBytes);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (out != null) {
                try {
                    out.flush();
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public boolean delete(String filePath) {
        File pictureFile = new File(path + File.separator + filePath);
        return pictureFile.delete();
    }

    public boolean deleteFile(String filePath) {
        File file = new File(filePath);
        return file.delete();
    }

    public boolean delete(String filePath, String fileName) {
        File file = new File(filePath, filePath);
        return file.delete();
    }

    public byte[] readFile(String fileName) {
        BufferedInputStream in = null;
        try {
            in = new BufferedInputStream(new FileInputStream(new File(path + "/" + fileName)));
            ByteArrayOutputStream baos = new ByteArrayOutputStream();

            byte[] buffer = new byte[8192];
            int count = -1;
            while((count = in.read(buffer)) != -1){
                baos.write(buffer, 0, count);
            }

            return baos.toByteArray();
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException ignore) {
                }
            }
        }
    }

    public byte[] readFile(String fold, String fileName) {
        fileName = fold + "/" + fileName;
        return readFile(fileName);
    }

    public static List<MultipartFile> springUpload(MultipartHttpServletRequest multipartRequest){
        List<MultipartFile> fileList = new ArrayList<MultipartFile>();
        if(multipartRequest != null) {
            for (Iterator<String> it = multipartRequest.getFileNames(); it.hasNext(); ) {
                String key = it.next();
                MultipartFile file = multipartRequest.getFile(key);
                if (file.getOriginalFilename().length() > 0) {
                    fileList.add(file);
                }
            }
        }
        return fileList;
    }

    public List<OtherResource> saveMultipartFiles(List<MultipartFile> multipartFiles, String fold) throws IOException{
        List<OtherResource> resources = new ArrayList<OtherResource>();
        String nowDate = DateUtil.getNowDate();
        Date date = new Date();
        for(MultipartFile multipartFile : multipartFiles) {
            String originalFilename = multipartFile.getOriginalFilename();
            String fileName = getFileName(date, originalFilename);
            OtherResource resource = new OtherResource();
            resource.setResourceName(fileName);
            resource.setResourceOriginal(originalFilename);
            resource.setFileSize(new Long(multipartFile.getSize()).intValue());
            resource.setStatus(IDBConstant.LOGIC_STATUS_YES);
            resource.setResourcePath(fold + File.separator + fileName);
            resource.setCreateTime(nowDate);
            resource.setResourceServiceId(IDBConstant.ZERO); //上传之后修改
            resource.setResourceServiceType(StrUtil.EMPTY); //上传之后修改
            resource.setResourceType(StrUtil.EMPTY); //上传之后修改
            resources.add(resource);
            saveToRootDisc(multipartFile.getInputStream(), fold, fileName);
        }
        return resources;
    }

    public String getFileName(Date date, String originalFilename) {
        if(date == null) date = new Date();
        return DateUtil.formatDate(date, DateUtil.YYYYMMDD) + IPlatformConstant.STR_LINE + StrUtil.getUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));
    }

}
